//
//  HRHomeViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-8.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRHomeViewController.h"

#import "HRGoodsSearchViewController.h"
#import "HRGoodsListViewController.h"
#import "HRGoodsInfoViewController.h"
#import "HRActivityInfoViewController.h"

#import "WebViewJavascriptBridge.h"

#define WEB_METHOD_SHOW_GOODSINFO @"clickProductRecommend"
#define WEB_METHOD_SHOW_ACTIVITYINFO @"clickActivityRecommend"


@interface HRHomeViewController (){
    BOOL _isLoaded;
}
@property(nonatomic,strong) WebViewJavascriptBridge *bridge;
@property (weak, nonatomic) IBOutlet UIWebView *webView;

@end

@implementation HRHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //解决布局问题
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        self.edgesForExtendedLayout=UIRectEdgeNone;
    }
    
    //显示主页内容
    _webView.delegate=self;
    
    //显示搜索框
    [self showSearchBarInNavigation];
    
    //注册"打开商品列表页面"通知事件
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showGoodsList:) name:NOTIFICATION_SHOW_GOODSLIST object:nil];
    
    
    //初始化JavascriptBridge
    [self initWebJavscriptBridge];
    
    _isLoaded=YES;//标记为第一次加载
}

-(void)viewWillAppear:(BOOL)animated{
    

    if (_isLoaded) {
        
        [self loadWebView];
        _isLoaded=NO;//标记为不是第一次加载
    }
    
    [super viewWillAppear:animated];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//初始化构建Bridge控件
-(void)initWebJavscriptBridge{
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView webViewDelegate:self handler:nil];
    
    //显示“商品详细信息”页面
    [_bridge registerHandler:WEB_METHOD_SHOW_GOODSINFO handler:^(id data, WVJBResponseCallback responseCallback) {
        [self showGoodsInfo:data];
    }];
    
    //显示“活动详细信息”页面
    [_bridge registerHandler:WEB_METHOD_SHOW_ACTIVITYINFO handler:^(id data, WVJBResponseCallback responseCallback) {

        [self showActivityInfo:data];
    }];
    
}

//加载首页
-(void)loadWebView{
    
    //隐藏无网络页面
    [self hideHud];
    
    NSURL *homeUrl=[NSURL URLWithString:URL_WAP_HOME];
    

    [self showCustomLoadingHud:kLoading inView:nil];
    [self.webView loadRequest:[NSURLRequest requestWithURL:homeUrl] progress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    } success:^NSString *(NSHTTPURLResponse *response, NSString *HTML) {
        [self hideCustomLoadingHud];
        //页面加载耗时
        [self analysisEnd:@"首页"];
        return HTML;
    } failure:^(NSError *error) {
        [self hideCustomLoadingHud];
        
        //显示无网络页面
        [self showHudByType:HUDTYPE_NO_WIFI];
    }];
    
    
}

#pragma mark - Methods
-(void)showSearchBarInNavigation{
    
    UIImageView *searchView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 290, 30)];
    UIImage *image=[[UIImage imageNamed:@"search_bg"]resizableImageWithCapInsets:UIEdgeInsetsMake(2, 2, 2, 2)];
    [searchView setImage:image];
    
    UIImage *iconImage=[UIImage imageNamed:@"search_ico"];
    CGSize iconSize=iconImage.size;
    UIImageView *iconImageView=[[UIImageView alloc]initWithFrame:CGRectMake(6, 7, iconSize.width,iconSize.height)];
    [iconImageView setImage:iconImage];
    [searchView addSubview:iconImageView];
    
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(25, 0, 150, 30)];
    label.text=@"搜索海尔商品";
    label.textColor=[UIColor colorFromHexRGB:@"dcdcdc"];
    label.font=[UIFont fontWithName:FONT_NAME_DEFAULT size:12];
    [searchView addSubview:label];
    
    [searchView setUserInteractionEnabled:YES];//允许事件
    
    UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showSearchGoods)];
    
    [searchView addGestureRecognizer:tapGesture];

    self.navigationItem.titleView=searchView;
}

//显示搜索页面
-(void)showSearchGoods{

    HRGoodsSearchViewController *goodsSearchViewController=[[HRGoodsSearchViewController alloc]initWithStyle:UITableViewStylePlain];
    
    [self.tabBarController.navigationController pushViewController:goodsSearchViewController animated:YES];
    
}


//显示商品列表(根据搜索条件 )
-(void)showGoodsList:(NSNotification *)notification{
    NSString *searchText=(NSString *)[notification object];
    
    //pop to rootview
    [self.tabBarController.navigationController popToRootViewControllerAnimated:NO];
    
    HRGoodsListViewController *goodsListViewController=[[HRGoodsListViewController alloc]initWithNibName:NIBNAME_GOODSLIST bundle:nil];
    goodsListViewController.searchContent=searchText;//搜索条件
    goodsListViewController.type=TYPE_PRODUCT_LIST_BY_SEARCH;
    
    [self.tabBarController.navigationController pushViewController:goodsListViewController animated:YES];
}

//显示指定商品的商品信息页
-(void)showGoodsInfo:(NSString *)Param{
    
    NSDictionary *paramJson=(NSDictionary *)[Param toArrayOrDictionary];
    
    NSString *productId=[paramJson objectForKey:@"productId"];
    HRGoodsInfoViewController *goodsInfoViewController=[[HRGoodsInfoViewController alloc]initWithNibName:NIBNAME_GOODSINFO bundle:nil];
    
    goodsInfoViewController.goodsId=productId;
    
    [self.tabBarController.navigationController pushViewController:goodsInfoViewController animated:YES];
}

//显示指定活动的详细页面
-(void)showActivityInfo:(NSString *)Param{
    
    
    NSDictionary *paramJSON=(NSDictionary *)[Param toArrayOrDictionary];
    
    NSString *productId=[paramJSON objectForKey:@"productId"];
    NSString *productName=[paramJSON objectForKey:@"productName"];
    NSString *productWebURL=[paramJSON objectForKey:@"productWebURL"];
    
    HRActivityInfoViewController *activityInfoViewController=[[HRActivityInfoViewController alloc]initWithNibName:NIBNAME_ACTIVITY bundle:nil];
    
    activityInfoViewController.productId=productId;
    activityInfoViewController.productName=productName;
    NSString *urlParam=[NSString stringWithFormat:@"?%@",URL_WAP_PARAM_FLAG];
    activityInfoViewController.urlStr=[productWebURL stringByAppendingString:urlParam];
    
    [self.tabBarController.navigationController pushViewController:activityInfoViewController animated:YES];
    
}


#pragma mark - HRProgress Delegate methods
//重新加载
-(void)tapHUDButtonAction:(id)button{
    [self loadWebView];
}

@end
